#pragma once

#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

const int backlog = 10; // 可以加const修饰
Log lg;

enum
{
    Sock_Error = 1,
    Bind_Error,
    Listen_Error
};

class Socket
{
public:
    void CreateSock()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0)
        {
            // 错误时输出错误信息
            lg(Fatal, "sock create error, %d:%s", errno, strerror(errno));
            exit(Sock_Error);
        }
    }

    // void Bind(const std::string ip, uint16_t port)
    void Bind(uint16_t port)
    {
        sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        // inet_pton(AF_INET, ip.c_str(), &server.sin_addr);
        // 地址无需自己指定
        server.sin_addr.s_addr = INADDR_ANY;

        if (bind(sockfd_, (const sockaddr *)&server, sizeof(server)) < 0)
        {
            lg(Fatal, "bind error, %d:%s", errno, strerror(errno));
            exit(Bind_Error);
        }
    }

    // bool Listen()
    void Listen()
    {
        if (listen(sockfd_, backlog) < 0)
        {
            lg(Fatal, "listen error, %d:%s", errno, strerror(errno));
            exit(Listen_Error); // 直接退出即可
        }
        //     return false;
        // return true;
    }

    int Accept(std::string *client_ip, uint16_t *client_port)
    {
        sockaddr_in client;
        socklen_t len = sizeof(client);
        int fd = accept(sockfd_, (sockaddr *)&client, &len);
        // 如果创建失败直接退出，不再执行后续内容
        if (fd < 0)
        {
            lg(Fatal, "accept error, %d:%s", errno, strerror(errno));
            return -1;
        }
        char buff[64];
        *client_ip = inet_ntop(AF_INET, &client.sin_addr, buff, sizeof(buff));
        *client_port = ntohs(client.sin_port);
        return fd;
    }

    bool Connect(const std::string &ip, uint16_t port)
    {
        sockaddr_in server;
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &server.sin_addr);
        int ret = connect(sockfd_, (sockaddr *)&server, sizeof(server));
        if (ret < 0)
        {
            lg(Fatal, "connect to [%s:%d] server error", ip, port);
            return false;
        }
        return true;
    }

    int GetSockFd()
    {
        return sockfd_;
    }

    void Close()
    {
        close(sockfd_);
    }

private:
    int sockfd_;
};